import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import {
  type IAirQuality,
  type ILocationData,
  weatherIncludesType,
  type WeatherIndices,
} from '@/types/weather'
import { WeatherService } from '@/services/weatherService'
import generalJWt from '@/Tools/generateJwt'

export const useWeatherStore = defineStore('weather', () => {
  // 状态
  const locations = ref<Map<string, ILocationData>>(new Map()) // 位置数据
  const currentLocationId = ref<string | null>(null) // 当前位置
  const defaultLocationId = ref<string | null>(null) // 默认位置
  const weatherIncludes = ref<WeatherIndices>(null) // 天气指数
  const isLoading = ref(false) // 是否正在加载
  const error = ref<string | null>(null) //报错信息

  const airQuality = ref<IAirQuality | null>(null) //空气质量
  /** 计算属性*/
  const allLocations = computed(() => Array.from(locations.value.values()))
  const currentLocation = computed(() =>
    currentLocationId.value ? locations.value.get(currentLocationId.value) : null,
  )
  const defaultLocation = computed(() =>
    defaultLocationId.value ? locations.value.get(defaultLocationId.value) : null,
  )
  const locationCount = computed(() => locations.value.size)
  // 获取空气质量
  const airQualityData = computed(() => airQuality.value)
  // 获取天气指数
  const weatherIncludesData = computed(() => weatherIncludes.value)

  // 检测JWT
  async function isExistsJwt() {
    const isExists = window.localStorage.getItem('jwt')
    const isexp = window.localStorage.getItem('jwtExp')
    const CurrentTime = Math.floor(Date.now() / 1000)

    if (isExists) {
      console.log('进入检测JWT')
      if (CurrentTime > Number(isexp)) {
        console.log('JWT已过期,重新生成JWT...')
        const res = await generalJWt()
        window.localStorage.setItem('jwt', res.jwt)
        window.localStorage.setItem('jwtExp', res.exp.toString())
        console.log(res)
      }
    } else {
      console.log('JWT不存在,重新生成JWT...')
      const res = await generalJWt()

      window.localStorage.setItem('jwt', res.jwt)
      window.localStorage.setItem('jwtExp', res.exp.toString())
      console.log(res)
    }
  }

  // 添加位置
  function addLocation(locationData: ILocationData) {
    // 添加位置到MAP
    locations.value.set(locationData.id, locationData)

    // 如果是默认位置，设置默认位置ID
    if (locationData.isDefault) {
      defaultLocationId.value = locationData.id
    }

    // 如果是当前位置，设置当前位置ID
    if (locationData.isCurrent) {
      currentLocationId.value = locationData.id
    }
  }

  // 更新位置天气
  function updateLocationWeather(locationId: string, weather: any) {
    const location = locations.value.get(locationId)
    if (location) {
      location.weather = weather
      locations.value.set(locationId, location)
    }
  }

  // 设置当前位置
  function setCurrentLocation(locationId: string) {
    // 清除之前的当前状态
    allLocations.value.forEach((location) => {
      location.isCurrent = false
    })

    // 设置新的当前位置
    const location = locations.value.get(locationId)
    if (location) {
      location.isCurrent = true
      currentLocationId.value = locationId
      locations.value.set(locationId, location)
    }
  }

  // 删除位置
  function removeLocation(locationId: string) {
    locations.value.delete(locationId)

    // 如果删除的是当前或默认位置，需要重新设置
    if (currentLocationId.value === locationId) {
      currentLocationId.value = defaultLocationId.value
    }
    if (defaultLocationId.value === locationId) {
      defaultLocationId.value = allLocations.value[0]?.id || null
    }
  }

  // 根据名称获取位置
  function getLocationByName(name: string): ILocationData | undefined {
    return allLocations.value.find((location) => location.name === name)
  }
  //根据ID获取位置
  function getLocationById(id: string): ILocationData | undefined {
    return allLocations.value.find((location) => location.id === id)
  }

  // 根据索引获取位置
  function getLocationByIndex(index: number): ILocationData | undefined {
    return allLocations.value[index]
  }

  // 初始化默认位置
  async function initializeDefaultLocation() {
    try {
      isLoading.value = true
      error.value = null

      // 检测JWT
      await isExistsJwt()

      // 获取默认位置
      const defaultLocationData = await WeatherService.initializeDefaultLocation()
      addLocation(defaultLocationData)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '初始化失败'
      console.error('初始化默认位置失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  // 搜索并添加位置
  async function searchAndAddLocation(locationName: string) {
    try {
      isLoading.value = true
      error.value = null
      // 搜索后添加位置
      const locationData = await WeatherService.getLocationWithWeather(locationName)
      addLocation(locationData)

      return locationData
    } catch (err) {
      error.value = err instanceof Error ? err.message : '搜索位置失败'
      console.error('搜索位置失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // 刷新位置天气
  async function refreshLocationWeather(locationId: string) {
    try {
      const location = locations.value.get(locationId)
      if (!location) return

      const weather = await WeatherService.getWeather(locationId)
      updateLocationWeather(locationId, weather)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '刷新天气失败'
      console.error('刷新天气失败:', err)
    }
  }

  /**
   获取空气质量
   */
  async function getAirQuality(latitude: string | number, longitude: string | number) {
    airQuality.value = await WeatherService.fetchAirQuality(latitude, longitude)
  }

  /**
   * 获取天气指数
   * @param days 天数
   * @param location 位置
   * @param type 类型
   */
  async function getweatherIndices(
    days: number,
    location: string,
    type: weatherIncludesType = weatherIncludesType.ALL,
  ) {
    const weatherIndices = await WeatherService.getweatherIndices(days, location, type)
    weatherIncludes.value = weatherIndices
    return weatherIndices
  }

  return {
    // 状态
    locations,
    currentLocationId,
    defaultLocationId,
    isLoading,
    error,
    weatherIncludes,
    // 计算属性
    allLocations,
    currentLocation,
    defaultLocation,
    locationCount,
    airQualityData,
    weatherIncludesData,
    // 方法
    isExistsJwt,
    addLocation,
    updateLocationWeather,
    setCurrentLocation,
    removeLocation,
    getLocationByName,
    getLocationByIndex,
    initializeDefaultLocation,
    searchAndAddLocation,
    refreshLocationWeather,
    getAirQuality,
    getweatherIndices,
    getLocationById,
  }
})
